package com.example.ajaxdemo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 异网短信接口
 *
 * @author wangfeng
 */
@Component
public class NewSmsInterf {
    //公网接口
    public static final String PUBLICNET = "http://202.102.221.75:18006/pay/sendOtherTeleSms.action";
    //电信专用接口
    public static final String TELECOM = "http://202.102.221.125:18001/tyyy/sendSms";

    public static Map<String,String> sendMsg(String url, String recvNum, String strMsg, String ip) {
        String msgSign = "通信平台";
        Map fb = new HashMap();
        try {
            String reqBody = JSON.toJSONString(getAllParam(recvNum.trim(), msgSign, strMsg));
            System.err.println("外网用户发送短信请求报文：" + reqBody);
            HttpClient client = new HttpClient();
            PostMethod method = new PostMethod(url);
            method.getParams().setContentCharset("UTF-8");
            method.setRequestBody(reqBody);
            int statusCode = client.executeMethod(method);
            if (statusCode == 200) {
                String returnMsg = method.getResponseBodyAsString();
                System.err.println("外网用户发送短信请求响应：" + returnMsg);
                JSONObject jsonResult = JSONObject.parseObject(returnMsg);
                String returnstatus = jsonResult.getString("returnstatus");
                if (!"Success".equalsIgnoreCase(returnstatus)) {
                    fb.put("resultCode", "-1");
                    fb.put("resultMessage", jsonResult.getString("message"));
                    System.err.println("发送短信失败，" + jsonResult.getString("message"));
                } else {
                    fb.put("resultCode", "0");
                    fb.put("resultMessage", jsonResult.getString("message"));
                }
            } else {
                fb.put("resultCode", "-1");
                fb.put("resultMessage", "发送失败！");
                System.err.println("发送短信失败，请求返回状态：" + statusCode);
            }
        } catch (Exception e1) {
            fb.put("resultCode", "-1");
            fb.put("resultMessage", "发送失败！");
            System.err.println("异网短信发送失败");
        } finally {
            return fb;
        }

    }

/*    public static FormBody YxsendMsg(String recvNum, String strMsg, String ip) {
        //线上短信地址
        String url = "http://192.168.0.32:18001/tyyy/sendOtherAdSms";
        String url="http://202.102.221.75:18006/pay/sendOtherAdSms.action";
        String msgSign = "通信平台";
        FormBody fb = new FormBody();
        try {
            String reqBody = JSON.toJSONString(getAllParam(recvNum.trim(), msgSign, strMsg.trim()));
            log.warn("外网用户发送短信请求报文：" + reqBody);
            HttpClient client = new HttpClient();
            PostMethod method = new PostMethod(url);
            method.getParams().setContentCharset("UTF-8");
            method.setRequestBody(reqBody);
            int statusCode = client.executeMethod(method);
            if (statusCode == 200) {
                String returnMsg = method.getResponseBodyAsString();
                log.warn("外网用户发送短信请求响应：" + returnMsg);
                JSONObject jsonResult = JSONObject.parseObject(returnMsg);
                String returnstatus = jsonResult.getString("returnstatus");
                if (!"Success".equalsIgnoreCase(returnstatus)) {
                    fb.append("resultCode", "-1");
                    fb.append("resultMessage", jsonResult.getString("message"));
                    log.error("发送短信失败，" + jsonResult.getString("message"));
                } else {
                    fb.append("resultCode", "0");
                    fb.append("resultMessage", jsonResult.getString("message"));
                }
            } else {
                fb.append("resultCode", "-1");
                fb.append("resultMessage", "发送失败！");
                log.error("发送短信失败，请求返回状态：" + statusCode);
            }
        } catch (Exception e1) {
            fb.append("resultCode", "-1");
            fb.append("resultMessage", "发送失败！");
            log.error("异网短信发送失败", e1);
        } finally {
            return fb;
        }

    }*/

    public static Map<String, Object> getAllParam(String serviceNbr, String sign, String msg) throws UnsupportedEncodingException {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("in", getInparam(serviceNbr, sign, msg));
        param.put("sec", getSec(serviceNbr, sign, msg));
        return param;
    }

    public static Map<String, String> getSec(String serviceNbr, String sign, String msg) throws UnsupportedEncodingException {
        Map<String, String> param = new HashMap<String, String>();
        param.put("mac", getMac(serviceNbr, sign, msg));
        param.put("orgId", "2");
        param.put("systemId", "3");
        //param.put("systemId", "6");
        return param;
    }

    public static Map<String, String> getInparam(String serviceNbr, String sign, String msg) throws UnsupportedEncodingException {
        Map<String, String> param = new HashMap<String, String>();
        param.put("serviceNbr", serviceNbr);
        param.put("sign", sign);
        param.put("msg", msg);
        return param;
    }

    private static String getMac(String serviceNbr, String sign, String msg) throws UnsupportedEncodingException {
        Map<String, String> sParaTemp = new HashMap<String, String>();
          /*sign = URLEncoder.encode(sign, "UTF-8");
          msg = URLEncoder.encode(serviceNbr, "UTF-8");*/
        sParaTemp.put("serviceNbr", serviceNbr);
        sParaTemp.put("sign", sign);
        sParaTemp.put("msg", msg);
        //String mac = "26broadband@125" + createLinkString(sParaTemp);
        String mac = "23Allmedia@#0722ss" + createLinkString(sParaTemp);
        return MD5Encrypt.MD5Encode(mac);
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param sParaTemp 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> sParaTemp) {
        try {
            List<String> keys = new ArrayList<String>(sParaTemp.keySet());
            StringBuilder prestr = new StringBuilder();
            Collections.sort(keys);
            for (int i = 0; i < keys.size(); i++) {
                String key = keys.get(i);
                String value = sParaTemp.get(key);
                prestr.append(key).append(value);
            }
            return prestr.toString();
        } catch (Exception e) {
            return "";
        }
    }

    public String sendSms(String phone, String code) {
//        int code = (int)((Math.random()*9+1)*100000);
        if (OperatorInspection.isChinaTelecomPhoneNum(phone)) {//电信用户
            new NewSmsInterf().sendMsg(NewSmsInterf.TELECOM, phone,code + "为您本次操作的验证码，5分钟内有效。请勿向他人透漏短信内容，如非本人操作，请忽略。", "127.0.0.1");
        }else {
            new NewSmsInterf().sendMsg(NewSmsInterf.PUBLICNET, phone,code + "为您本次操作的验证码，5分钟内有效。请勿向他人透漏短信内容，如非本人操作，请忽略。", "127.0.0.1");
        }
        return code + "";
    }


    public static void main(String[] args) {
//        String smsPhone = "18119642738";
        String smsPhone = "17856698156";
        if (OperatorInspection.isChinaTelecomPhoneNum(smsPhone)) {//电信用户
            new NewSmsInterf().sendMsg(NewSmsInterf.TELECOM, smsPhone,"263754为您本次操作的验证码，5分钟内有效。请勿向他人透漏短信内容，如非本人操作，请忽略。", "127.0.0.1");
        }else {
            new NewSmsInterf().sendMsg(NewSmsInterf.PUBLICNET, smsPhone,"163754为您本次操作的验证码，5分钟内有效。请勿向他人透漏短信内容，如非本人操作，请忽略。", "127.0.0.1");
        }
       /* {"sec":{"systemId":"6","mac":"12086851285419223923319415017118828335148","orgId":"2"},"in":{"msg":"尊敬的用户，您预约办理的“{天天宽带20Mbps包年}”已下单成功，成功新装办理可享“{流程测试单}”，请您继续支付，我们将尽快完成业务受理，如已支付请忽略。","serviceNbr":"19909697263","sign":"通信平台"}}*/
//        new NewSmsInterf().sendMsg("19909697263", "尊敬的用户，您预约办理的“天天宽带20Mbps包年”已下单成功，成功新装办理可享“流程测试单”，请您继续支付，我们将尽快完成业务受理，如已支付请忽略。", "127.0.0.1");
//        new NewSmsInterf().sendMsg("15305512053", 203754+"为您本次操作的验证码，5分钟内有效。请勿向他人透漏短信内容，如非本人操作，请忽略。", "127.0.0.1");
    }
}
